package com.example.notuikitimdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMGroupAddOpt;
import com.tencent.imsdk.TIMGroupEventListener;
import com.tencent.imsdk.TIMGroupManager;
import com.tencent.imsdk.TIMGroupReceiveMessageOpt;
import com.tencent.imsdk.TIMGroupTipsElem;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMMessageUpdateListener;
import com.tencent.imsdk.TIMRefreshListener;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUserConfig;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.group.GroupBaseManager;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    final String tag = "yanze";
    private TIMConversation conversation;//会话

    private EditText et_input;
    private Button btn_send;
    private TextView tv_print;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_input = findViewById(R.id.et_input);
        btn_send = findViewById(R.id.btn_send);
        btn_send.setOnClickListener(this);
        tv_print = findViewById(R.id.tv_print);
        findViewById(R.id.btn_create_group).setOnClickListener(this);
        findViewById(R.id.btn_delete_group).setOnClickListener(this);
        findViewById(R.id.btn_add_group).setOnClickListener(this);
        findViewById(R.id.btn_exit_group).setOnClickListener(this);

        userConfig();
        login();
    }

    //用户配置
    private void userConfig() {
        //基本用户配置
        TIMUserConfig userConfig = new TIMUserConfig()
                //设置用户状态变更事件监听器
                .setUserStatusListener(new TIMUserStatusListener() {
                    @Override
                    public void onForceOffline() {
                        //被其他终端踢下线
                        Log.i(tag, "onForceOffline");
                    }

                    @Override
                    public void onUserSigExpired() {
                        //用户签名过期了，需要刷新 userSig 重新登录 IM SDK
                        Log.i(tag, "onUserSigExpired");
                    }
                })
                //设置连接状态事件监听器
                .setConnectionListener(new TIMConnListener() {
                    @Override
                    public void onConnected() {
                        Log.i(tag, "onConnected");
                    }

                    @Override
                    public void onDisconnected(int code, String desc) {
                        Log.i(tag, "onDisconnected");
                    }

                    @Override
                    public void onWifiNeedAuth(String name) {
                        Log.i(tag, "onWifiNeedAuth");
                    }
                })
                //设置群组事件监听器
                .setGroupEventListener(new TIMGroupEventListener() {
                    @Override
                    public void onGroupTipsEvent(TIMGroupTipsElem elem) {
                        Log.i(tag, "onGroupTipsEvent, type: " + elem.getTipsType());
                    }
                })
                //设置会话刷新监听器
                .setRefreshListener(new TIMRefreshListener() {
                    @Override
                    public void onRefresh() {
                        Log.i(tag, "onRefresh");
                    }

                    @Override
                    public void onRefreshConversation(List<TIMConversation> conversations) {
                        Log.i(tag, "onRefreshConversation, conversation size: " + conversations.size());
                    }
                });
        //禁用本地所有存储
        userConfig.disableStorage();
        //开启消息已读回执
        userConfig.enableReadReceipt(true);
        //将用户配置与通讯管理器进行绑定
        TIMManager.getInstance().setUserConfig(userConfig);
    }

    private void addNewMsgListener() {
        //添加消息监听器
        TIMManager.getInstance().addMessageListener(new TIMMessageListener() {
            @Override
            public boolean onNewMessages(List<TIMMessage> list) {
                String msg = parseTxt(list.get(0));
                Toast.makeText(MainActivity.this, "addMessageListener收到新消息:" + msg + " " + list.size(), Toast.LENGTH_SHORT).show();
                Log.i(tag, "addMessageListener收到新消息:" + msg + " " + list.size());
                return false;
            }
        });
    }

    //登录
    private void login() {
        // identifier 为用户名，userSig 为用户登录凭证
        String userSig = GenerateTestUserSig.genTestUserSig(Constants.userid);
        TIMManager.getInstance().login(Constants.userid, userSig, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                //错误码 code 列表请参见错误码表
                Toast.makeText(MainActivity.this, "登录失败！" + desc, Toast.LENGTH_SHORT).show();
                Log.d(tag, "login failed. code: " + code + " errmsg: " + desc);
            }

            @Override
            public void onSuccess() {
                Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                Log.d(tag, "login succ");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_send:
                Toast.makeText(this, "发送消息!", Toast.LENGTH_SHORT).show();
                String msg = et_input.getText().toString().trim();

                //构造一条消息
                TIMMessage timMessage = new TIMMessage();

                //添加文本内容
                TIMTextElem textElem = new TIMTextElem();
                textElem.setText(msg);

                //添加文本到消息中
                timMessage.addElement(textElem);

                conversation.sendOnlineMessage(timMessage, new TIMValueCallBack<TIMMessage>() {
                    @Override
                    public void onError(int i, String s) {
                        Toast.makeText(MainActivity.this, "发送失败:" + i + " " + s, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSuccess(TIMMessage timMessage) {
                        Toast.makeText(MainActivity.this, "发送成功！" + parseTxt(timMessage), Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.btn_create_group:
                Toast.makeText(this, "创建群组", Toast.LENGTH_SHORT).show();
                createRoom();
                break;
            case R.id.btn_delete_group:
                deleteGroup();
                break;
            case R.id.btn_add_group:
                addGroup();
                break;
                case R.id.btn_exit_group:
                exitGroup();
                break;
        }
    }

    //获取群组回话
    private void getGroupConversation() {
        conversation = TIMManager.getInstance().getConversation(TIMConversationType.Group, Constants.roomid);
        addNewMsgListener();
    }

    //解析文本类型消息
    private String parseTxt(TIMMessage timMessage) {
//        timMessage.isRead();//已读；
//        timMessage.status();//消息状态
//        timMessage.isSelf();//自己发的
        //timMessage.getSenderNickname();// 昵称
//        timMessage.getSenderProfile();//获取发送者资料
//        timMessage.getSenderGroupMemberProfile();//获取所在群资料

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < timMessage.getElementCount(); i++) {
            TIMElem elem = timMessage.getElement(i);

            //获取消息类型
            TIMElemType elemType = elem.getType();
            if (elemType == TIMElemType.Text) {
                sb.append(((TIMTextElem) elem).getText());
            }
        }
        return sb.toString();
    }

    /**
     * 创建聊天室
     */
    public void createRoom() {
        // type 群类型, 目前支持的群类型：私有群（Private）、公开群（Public）、 聊天室（ChatRoom）、音视频聊天室（AVChatRoom）和在线成员广播大群（BChatRoom）
        TIMGroupManager.CreateGroupParam param = new TIMGroupManager.CreateGroupParam("Public","test_group");
        //设置要创建的群的群ID setGroupId
        param.setGroupId(Constants.roomid);
        //设置要创建的群的群公告 setNotification
        param.setNotification("welcome to our group");
        //设置要创建的群的群简介 setIntroduction
        param.setIntroduction("hello world");
        //设置要创建的群的群头像 setFaceUrl

        //设置要创建的群的加群选项 setAddOption(TIMGroupAddOpt option)
        param.setAddOption(TIMGroupAddOpt.TIM_GROUP_ADD_ANY);

        //设置要创建的群允许的最大成员数 setMaxMemberNum(long maxMemberNum)

        //设置要创建的群的初始成员 setMembers(List<TIMGroupMemberInfo> infos)
//        List<TIMGroupMemberInfo> infos = new ArrayList<TIMGroupMemberInfo>();
//        TIMGroupMemberInfo member = new TIMGroupMemberInfo("cat");
//        infos.add(member);
//        param.setMembers(infos);

        //接收群消息，但若离线情况下则不会推送离线消息
//        TIMGroupManager.ModifyMemberInfoParam param1 = new TIMGroupManager.ModifyMemberInfoParam(Constants.roomid, Constants.userid);
//        param1.setReceiveMessageOpt(TIMGroupReceiveMessageOpt.NotReceive);

        //创建群组
        TIMGroupManager.getInstance().createGroup(param, new TIMValueCallBack<String>() {
            @Override
            public void onError(int code, String desc) {
                Toast.makeText(MainActivity.this, "群创建失败：" + code + " " + desc, Toast.LENGTH_SHORT).show();
                Log.d(tag, "create group failed. code: " + code + " errmsg: " + desc);
            }

            @Override
            public void onSuccess(String s) {
                Toast.makeText(MainActivity.this, "群创建成功！" + s, Toast.LENGTH_SHORT).show();
                Log.d(tag, "create group succ, groupId:" + s);
                getGroupConversation();
            }
        });
    }

    /**
     * 解散群组
     */
    public void deleteGroup() {
        TIMGroupManager.getInstance().deleteGroup(Constants.roomid, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Log.i(tag, "解散失败！");
            }

            @Override
            public void onSuccess() {
                Log.i(tag, "解散成功~");
            }
        });
    }

    /**
     * 加群
     */
    public void addGroup() {
        TIMGroupManager.getInstance().applyJoinGroup(Constants.roomid, "some reason", new TIMCallBack() {
            @java.lang.Override
            public void onError(int code, String desc) {
                //接口返回了错误码 code 和错误描述 desc，可用于原因
                //错误码 code 列表请参见错误码表
                Log.e(tag, "applyJoinGroup err code = " + code + ", desc = " + desc);
                Toast.makeText(MainActivity.this, "加群失败：" + code + " " + desc, Toast.LENGTH_SHORT).show();
            }

            @java.lang.Override
            public void onSuccess() {
                Log.i(tag, "applyJoinGroup success");
                Toast.makeText(MainActivity.this, "加群成功！", Toast.LENGTH_SHORT).show();
                getGroupConversation();
            }
        });
    }

    /**
     * 退群
     */
    public void exitGroup() {
        TIMGroupManager.getInstance().quitGroup(Constants.roomid, new TIMCallBack() {
            @Override
            public void onError(int i, String s) {
                Toast.makeText(MainActivity.this, "退群失败：" + i + " "  + s, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess() {
                Toast.makeText(MainActivity.this, "退出成功！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void loginout() {
        //登出
        TIMManager.getInstance().logout(new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {

                //错误码 code 和错误描述 desc，可用于定位请求失败原因
                //错误码 code 列表请参见错误码表
                Log.d(tag, "logout failed. code: " + code + " errmsg: " + desc);
            }

            @Override
            public void onSuccess() {
                //登出成功
            }
        });
    }


}
